<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>奖励设置</title>

  <link rel="stylesheet" href="https://qiye.sophp.cn/fission/css/layui.css">
  <link rel="stylesheet" href="https://qiye.sophp.cn/fission/css/iconfont.css">
  <link rel="stylesheet" href="/unpkg/lib-master/theme-chalk/index.css"> 
  <link rel="stylesheet" href="https://qiye.sophp.cn/fission/css/common.css">

  <style>
    [v-cloak] {
      display: none;
    }
    /*公共头部带搜索*/
    .public_container{
      margin: 20px;
      background: #fff;
    }

    .stage-item-form .el-input__inner {
      max-width: 280px;
    }
    .stage-item-form .el-upload {
      width: 120px;
      height: 120px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .stage-item-form .avatar-uploader-icon { 
      font-size: 28px;
      line-height: 120px;
      color: #8c939d;
    }
    .stage-item-form__tips {
      font-size: 12px;
      color: red;
      line-height: 1;
      margin-top: 10px;
    }
  </style>
</head>

<body>

  <div id="app">
    <!-- 奖励设置 -->
    <section class="public_container" style="padding: 20px;">
      <h3>奖励设置</h3>
      <hr style="margin: 20px 0;">
      <div v-cloak class="flex">
        <el-tabs v-model="stageActive" type="card" closable
          style="max-width: 1000px;"
          @tab-remove="removeStage"
        >
          <el-tab-pane
            v-for="(stage, stageIndex) in stageRewards"
            :key="stageIndex"
            :label="stage.stagesort + '阶段奖励'"
            :name="stage.stagesort"
          >
            <el-form class="stage-item-form" label-width="130px" size="medium">

              <el-form-item label="奖励类型：">
                <el-radio-group v-model="stage.prize_type">
                  <el-radio v-for="prizeType in prizeTypes" :key="prizeType.value" :label="prizeType.value">!{!{ prizeType.title }}</el-radio>
                </el-radio-group>
                <!-- 这个提示是什么逻辑啊....真需要的话可以给对应的 input 加 :disabled="stage.fid" -->
                <p v-if="stage.prize_type === '3' || stage.prize_type === '5'"
                  class="stage-item-form__tips"
                >奖励!{!{ stage.prize_type === '3' ? '类型' : '名称' }}和任务人数请谨慎设置，一旦保存，不可更改</p>
              </el-form-item>

              <el-form-item v-show="fieldVisible('hxusers')" label="核销人员成员：" required>
                <el-button size="large" icon="el-icon-plus" @click="ButLISE(stageIndex)">添加核销成员</el-button>
                <span style="color: #848484;;padding-left: 5px;">可添加多个企业成员分别进行裂变</span>
                <div v-if="stage.hxusersHtml" v-html="stage.hxusersHtml" style="padding: 5px 0 0;"></div>
              </el-form-item>
              <input type="hidden" name="selectedhx" value="" id="selectedhx" />
              <input type="hidden" name="selectedhtml" value='' id="selectedhtml" />

              <el-form-item v-show="fieldVisible('stage_name')" label="奖品名称：">
                <el-input v-model="stage.stage_name" type="text" placeholder=""></el-input>
              </el-form-item>

              <el-form-item v-show="fieldVisible('stage_num')" label="活动人数：">
                <el-input v-model="stage.stage_num" type="number" :min="0" placeholder="即达到多少人助力可领"></el-input>
              </el-form-item>

              <el-form-item v-show="fieldVisible('s_num')" label="发放数量：">
                <el-input v-model="stage.s_num" type="number" :min="0" placeholder="总数量"></el-input>
              </el-form-item>

              <el-form-item v-show="fieldVisible('d_code_id')" label="选择兑换码：">
                <el-select style="width: 100%;max-width: 280px;" v-model="stage.d_code_id" placeholder="选择兑换码">
                  <el-option v-for="dcode in dCodeOptions" :key="dcode.value"
                    :label="dcode.name" :value="dcode.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item v-show="fieldVisible('redbag')" label="红包金额：">
                <el-input v-model="stage.redbag" type="number" :min="0" placeholder="每个红包的金额"></el-input>
              </el-form-item>

              <el-form-item v-show="fieldVisible('erwei_code')" label="自定义二维码：">
                <el-upload
                  action="upload_files.html"
                  :show-file-list="false"
                  :on-success="onStageQrcodeUploaded"
                >
                  <img v-if="stage.erwei_code" :src="stage.erwei_code" style="width:120px;height:120px;" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>

              <el-form-item v-show="fieldVisible('form_url')" label="表单链接：">
                <el-input v-model="stage.form_url" type="text" placeholder=""></el-input>
                <p class="stage-item-form__tips">可使用金数据,麦客crm等工具制表单</p>
              </el-form-item>

              <el-form-item v-show="fieldVisible('stage_describe')" label="文字描述：">
                <el-input v-model="stage.stage_describe" type="text" placeholder="文字描述"></el-input>
              </el-form-item>
              <el-form-item v-show="fieldVisible('pb_coupon_id')" label="发放优惠券：">
                <el-select v-model="stage.pb_coupon_id" placeholder="请选择">
                <el-option
                  v-for="item in pbCoupons" :key="item.id" :value="item.id" :label="item.name">
                </el-option>
              </el-select>
              </el-form-item>
              <el-form-item v-show="fieldVisible('pb_setlevel_id')" label="设置等级：">
                 <el-select v-model="stage.pb_setlevel_id" placeholder="请选择">
                  <el-option
                    v-for="item in pbLevels" :key="item.id" :value="item.id" :label="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <div class="flex-1" style="min-width: 100px;padding: 4px 10px;">
          <el-button size="small" @click="addStage">添加阶段</el-button>
        </div>
      </div>

      <div style="padding: 20px 130px;">
        <el-button size="small" type="primary"
          style="width: 120px;"
          @click="onSubmit"
        >保存</el-button>
        <el-button size="small" type="default"
          style="width: 120px;"
        >取消</el-button>
      </div>
    </section>
  </div>

  <!-- es6语法兼容包 -->
  <script src="https://qiye.sophp.cn/fission/js/layui.all.js"></script>
  <script src="/unpkg/unpkg.vue.js"></script>
  <script src="/unpkg/lib-master/index.js"></script>
  <script src="/js/ajax.js"></script>
  <script>
    /**
     * 创建一个新的阶段数据
     * @param {String} sort 阶段排序（第几阶段）
     */
    function createStageItem(sort = '1') {
      return {
        id: '',
        // fid: '',
        // wid: '',
        stagesort: sort,
        stage_name: '', // 奖品名称
        // stage_type: '1',
        stage_num: '', // 活动人数
        prize_type: '1', // 奖励类型
        form_url: '', // 表单链接
        erwei_code: '', // 自定义二维码
        // hx_code: '', // 核销码？
        hxusers: "[]", // 核销人员
        hxusersHtml: '',
        // hxusersDisabled: false, // 初始化时补上的，红字有提示说这玩意儿创建完后不允许修改
        redbag: null, // 红包金额
        // status: '0',
        s_num: null, // 发放数量
        d_code_id: null, // 兑换码id
        // dtime: null,
        // ctime: null,
        stage_describe: '', // 文字描述
        pb_coupon_id: null,
        pb_setlevel_id: null,
      }
    }
    // Vue 实例
    var app = new Vue({
      el: '#app',
      data: {
        // 兑换码选项铺在这里（原options）
        type:{$type},
        dCodeOptions:{$dhuanma},
        pb_exist: "{$pb_exist}",
        pbCoupons: {$pbCoupons},
        pbLevels: {$pbLevels},
        pbTitle: "{$pbTitle}",
        datas: {$qy_stage_prizes},
        // 奖励类型
        prizeTypes: [
          !{title: '自定义二维码', value: '1'},
          !{title: '表单', value: '2'},
          !{title: '兑换码', value: '3'},
          !{title: '核销码', value: '4'},
          !{title: '红包', value: '5'},
        ],
        // 当前选中阶段
        stageActive: '1',
        // 阶段奖励数据铺在这里（原boxdata）
        stageRewards: {$qy_stage_prizes},
      },
      computed: {
        
        currentStage() {
          return this.stageRewards.find(e => e.stagesort === this.stageActive)
        }
      },
      mounted() {
        console.log(this.datas);
        if(this.pb_exist && this.type != 2) this.prizeTypes.push(!{title: this.pbTitle, value: '6'});
        if(this.datas.length) {
           for (var i = 0; i < this.datas.length; i++) {
             this.stageRewards[i] = {
                  stagesort: this.datas[i].stagesort,
                  stage_name: this.datas[i].stage_name, // 奖品名称
                  // stage_type: '1',
                  stage_num: this.datas[i].stage_num, // 活动人数
                  prize_type: this.datas[i].prize_type, // 奖励类型
                  form_url: this.datas[i].form_url, // 表单链接
                  erwei_code: this.datas[i].erwei_code, // 自定义二维码
                  // hx_code: '', // 核销码？
                  hxusers: this.datas[i].hxusers, // 核销人员
                  hxusersHtml: this.datas[i].hxusersHtml,
                  // hxusersDisabled: false, // 初始化时补上的，红字有提示说这玩意儿创建完后不允许修改
                  redbag: this.datas[i].redbag, // 红包金额
                  // status: '0',
                  s_num: this.datas[i].s_num, // 发放数量
                  d_code_id: this.datas[i].d_code_id, // 兑换码id
                  // dtime: null,
                  // ctime: null,
                  stage_describe: this.datas[i].stage_describe, // 文字描述
                  pb_coupon_id: this.datas[i].pb_coupon_id,
                  pb_setlevel_id: this.datas[i].pb_setlevel_id,
             }
           }
        }
        console.log(this.stageRewards)
        // 初始化，有需要处理的数据格式的话 可以在这儿处理
        // this.stageRewards = (this.stageRewards || []).map((stage) => {
        //   // const users = typeof stage.hxusers !== 'string' ? JSON.stringify(stage.hxusers) : stage.hxusers
        //   // 不允许修改，hxusers 有值的话，id是数字
        //   stage.hxusersDisabled = stage.prize_type === '4' && /\d/.test(users)
        //   return stage
        // })
        if (!this.stageRewards.length) this.addStage()
      },
      methods: {
        // 统一控制阶段下内容字段要不要显示，目前是根据 奖励类型（prize_type）判断
        fieldVisible(prop) {
          const stage = this.currentStage
          if (!stage) return false            
          const prizeType = stage.prize_type
          // 以下数组里是 prizeType，即哪些奖励类型下显示该内容字段的编辑
          switch (prop) {
            // 自定义二维码
            case 'erwei_code':
              return ['1'].includes(prizeType)
            // 表单链接
            case 'form_url':
              return ['2'].includes(prizeType)
            // 奖品名称
            case 'stage_name':
              return ['3', '5'].includes(prizeType)
            // 发放数量
            case 's_num':
              return ['3', '4', '5'].includes(prizeType)
            // 选择兑换码
            case 'd_code_id':
              return ['3'].includes(prizeType)
            // 核销人员，fid 可用于判断不可修改吗？保存过，并且 hxusers 有值（id是数字）
            case 'hxusers':
              return ['4'].includes(prizeType) && !stage.hxusersDisabled
            // 红包金额
            case 'redbag':
              return ['5'].includes(prizeType)
            // 活动人数
            case 'stage_num':
              return ['1', '2', '3', '4', '5'].includes(prizeType)
            // 文字描述
            case 'stage_describe':
              return ['1', '2', '3', '4', '5'].includes(prizeType)
            //点大发放优惠券
            case 'pb_coupon_id':
              return ['6'].includes(prizeType)
            //点大设置等级
            case 'pb_setlevel_id':
              return ['6'].includes(prizeType)
            default:
              return true
          }
        },
        // 添加阶段
        addStage() {
          const newStage = String(this.stageRewards.length + 1)
          this.stageRewards.push(createStageItem(newStage))
          this.stageActive = newStage
        },
        // 删除阶段
        removeStage(targetName) {
          const tabs = this.stageRewards
          // if (tabs.length <= 1) {
          //   alert('至少一个阶段奖励')
          //   return
          // }
          let active = this.stageActive
          const activeIndex = tabs.findIndex((e) => e.stagesort === active)
          const i = tabs.findIndex((e) => e.stagesort === targetName)
          if (active === targetName) {
            // const nextTab = tabs[i + 1] || tabs[i - 1]
            // nextTab && (active = nextTab.stagesort)
            // +1 的马上要因为移除而减回去，所以不变
            if (!tabs[i + 1] && tabs[i - 1]) {
              active = tabs[i - 1].stagesort
            }
          } else {
            // 因为马上要移除一个
            if (activeIndex > i) active = String(active - 1)
          }
          this.stageActive = active
          tabs.splice(i, 1)
          this.stageRewards = tabs.map((stage, stageIndex) => {
            stage.stagesort = String(stageIndex + 1)
            return stage
          })
          alert('注意：删除当前阶梯后，系统会删除当前阶梯的活动数据')
        },
        // 阶段-上传自定义二维码
        onStageQrcodeUploaded(res) {
          const activeIndex = this.stageRewards.findIndex(e => e.stagesort === this.stageActive)
          this.stageRewards[activeIndex].erwei_code = res.data.filePath
        },
        // 选择核销人员
        ButLISE(stageIndex) {
          layer.open({
            type: 2,
            title: '请选择使用人员',
            shadeClose: true,
            shade: 0.2,

            area: ['700px', '530px'],
            content: 'select_user-3.html',
            end: () => {
              var selectedhtml = document.getElementById('selectedhtml').value
              var selectedhx = document.getElementById('selectedhx').value
              Object.assign(this.stageRewards[stageIndex], {
                hxusers: selectedhx,
                // hxusers: JSON.stringify(selectedhx.split(',')),
                hxusersHtml: selectedhtml
              })
               this.stageRewards.splice(0, 0)
            }
          });
        },
        // 提交
        onSubmit() {
          const tabs = this.stageRewards
          for (let i = 0, l = tabs.length; i < l; i++) {
            const stage = tabs[i]
            // 需要前端数据验证的话
            // const prizeType = stage.prize_type
            // if (!stage.stage_num) {
            //   this.stageActive = stage.stagesort
            //   return alert(`请填写活动人数[阶段${i + 1}]`)
            // }
            // if (prizeType === '1') {
            //   if (!stage.erwei_code) {
            //     this.stageActive = stage.stagesort  
            //     return alert('请上传二维码') 
            //   }
            // }
            // ...

            // 处理 hxusers 数据格式
            if (Array.isArray(stage.hxusers)) {
              stage.hxusers = JSON.stringify(stage.hxusers)
            }
          }


          myAjaxPost(false, true, '', !{data:JSON.stringify(tabs)}, function (resp) {
            console.log(resp)
            if (resp.status == 'success') {
              tusi(resp.msg);
              // setTimeout(function(){
                // location.href = 'mission_list.html'; 
              // },2000);
            }else{
              alert(resp.msg);
            }
          });

          console.log('数据：', tabs)
          // alert('数据：' + JSON.stringify(tabs))
        }
      }
    })
  </script>
</body>
</html>
